package com.warren.filter;

import com.warren.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @version V1.0
 * @Description: 日志全局添加traceId
 * @author: warren
 * @date: 2022/8/5 16:39
 */
@Component
@Slf4j
public class TraceFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // "traceId"
        MDC.put("traceId", getTraceId());
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    private String getTraceId() {
//        long timestamp = System.currentTimeMillis();
//        UUID uuid = UUID.randomUUID();
//        String uniqueId = timestamp + uuid.toString().replace("-", "");
//        return uniqueId;
        String uniqueId = SnowFlake.nextStrId();
        return uniqueId;
    }
}